import { Component, OnInit } from '@angular/core';
import { UserService } from '../../../shared/service/user.service';
import { FunctionService } from '../../../shared/service/function.service';
import { LoginService } from '../../../shared/service/login.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {

  // 设置default name
  D_name: String = 'KA';

  // 当前登陆的用户
  user: any;

  kaClass: String = '';
  loading: Boolean;

  classArray: any[] = [];

  constructor(
    private userService: UserService,
    private functionService: FunctionService,
    private loginService: LoginService,
    private router: Router
  ) {
    this.loading = false;
    // 从登录中拿当前用户
    this.ifLogin();
  }

  ngOnInit() {
    // 初始化加载获取所有分类
    this.getClassAll();
  }

  /*****
  *  检查是否有用户登录
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  ifLogin() {
    this.user = this.loginService.user;
    if (!this.user) {
      this.router.navigateByUrl('/login');
    }
  }

  /*****
  *  初始化加载获取所有分类
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  getClassAll() {
    if (this.user) {
      this.userService.getClassAll()
        .then((data) => {
          this.classArray = this.functionService.clearObjToArray(data)
        });
    }
  }

  /*****
  *  create class 
  *  @param  :  (参数)
  *  @return :  (返回值说明)
  *****/
  createClass() {

    const cls = {
      name: this.kaClass
    };

    this.loading = true;

    this.userService.CreateClass(cls)
        .then((res) => {
          console.log(res)
          if (res['state'] === 200) {
            this.classArray = this.functionService.clearObjToArray(res['data']);
          }
          this.kaClass = '';
          this.loading = false;
        })

  }

}
